/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function (nums) {
  var max = 0;
  var sum = 0;
  var startIndex = 0;
  var endIndex = 0;

  nums.forEach(function (item, index, array) {
    sum += item;
    if (sum > max) {
      endIndex = index;
      max = sum;
    }
    if (sum < 0) {
      sum = 0;
      startIndex = index
    }
  });
  // console.log(startIndex, endIndex)

  // const newArr = nums.slice(startIndex + 1, endIndex + 1);
  // console.log(newArr) // 返回子数组

  return max;
};

console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) // 连续子数组 [4,-1,2,1] 的和最大，为 6 

/**
 * 最小子数组和
 */
var minSubArray = function (nums) {
  var min = 0;
  var sum = 0;
  var startIndex = 0;
  var endIndex = 0;

  nums.forEach(function (item, index, array) {
    sum += item;
    if (sum < min) {
      endIndex = index;
      min = sum;
    }
    if (sum > 0) {
      sum = 0;
      startIndex = index
    }
  });
  // console.log(startIndex, endIndex)

  const newArr = nums.slice(startIndex + 1, endIndex + 1);
  console.log(newArr) // 返回子数组

  return min;
};

console.log(minSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) // -5

/**
 * 长度最小的子数组
 */
var minSubArrayLen = function (target, nums) {
  // 长度计算一次
  const len = nums.length;
  let l = r = sum = 0,
    res = len + 1; // 子数组最大不会超过自身
  while (r < len) {
    sum += nums[r++];
    // 窗口滑动
    while (sum >= target) {
      // r始终为开区间 [l, r)
      res = res < r - l ? res : r - l;
      sum -= nums[l++];
    }
  }
  return res > len ? 0 : res;
};